package com.example.demolinux.service;

import com.example.demolinux.entity.User;
import com.example.demolinux.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    // 查询所有用户
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    // 根据ID查询用户
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }

    // 添加用户
    @Transactional
    public int addUser(User user) {
        return userMapper.insert(user);
    }

    // 更新用户
    @Transactional
    public int updateUser(User user) {
        return userMapper.update(user);
    }

    // 删除用户
    @Transactional
    public int deleteUser(Long id) {
        return userMapper.deleteById(id);
    }

    // 测试事务：添加两个用户
    @Transactional(rollbackFor = Exception.class)
    public String addTwoUsers(User user1, User user2) {
        System.out.println("[事务] 开始添加用户...");
        
        // 添加第一个用户
        userMapper.insert(user1);
        System.out.println("[事务] 已添加用户1: " + user1);

        // 模拟异常：如果第二个用户年龄为负数，抛出异常
        if (user2.getAge() < 0) {
            System.out.println("[事务] 年龄不能为负数，抛出异常！");
            throw new RuntimeException("年龄不能为负数");
        }

        // 添加第二个用户
        userMapper.insert(user2);
        System.out.println("[事务] 已添加用户2: " + user2);

        System.out.println("[事务] 添加成功，准备提交事务");
        return "添加成功";
    }

    // 清空所有用户
    @Transactional
    public int deleteAll() {
        return userMapper.deleteAll();
    }
}

